package com.ruoyi.visitor.service.impl;

/**
 * packageName com.ruoyi.visitor.service.impl
 *
 * @author wfx
 * @version JDK 8
 * @className WechatLoginServiceImpl
 * @date 2025/4/15
 * @description TODO
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.visitor.model.AccessToken;
import com.ruoyi.visitor.model.SessionInfo;
import org.springframework.stereotype.Service;

@Service
public class WechatLoginServiceImpl {
    private static final String AppID = "wx3ea1614d18758301";
    private static final String AppSecret = "0d426f5351133acb581310ca35445237";
    private static final String AUTH_URL = "https://api.weixin.qq.com/sns/jscode2session";

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    public static SessionInfo getSessionInfo(String code) {
        StringBuilder result = new StringBuilder();
        try {
            String requestUrl = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    AUTH_URL, AppID, AppSecret, code);
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        AccessToken ak = getAccessToken();
        System.out.println(JsonUtils.obj2json(ak));
        SessionInfo info = JsonUtils.json2pojo(result.toString(),SessionInfo.class);
        System.out.println(JsonUtils.obj2json(info));

        return info;
    }

    public static AccessToken getAccessToken(){
        String requestUrl = String.format(ACCESS_TOKEN_URL,AppID, AppSecret);
        String res = HttpUtils.sendGet(requestUrl);
        AccessToken ak = JsonUtils.json2pojo(res,AccessToken.class);
        return ak;
    }
}